package com.macro.mall.portal.component;

import com.macro.mall.portal.domain.QueueEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessageSender {
    private static Logger LOGGER = LoggerFactory.getLogger(MessageSender.class);
    @Autowired
    private AmqpTemplate amqpTemplate;

    public void sendMessage(Object message,final long delayTimes,QueueEnum queueEnum){
        //给延迟队列发送消息
        amqpTemplate.convertAndSend(queueEnum.getExchange(), queueEnum.getRouteKey(), message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //给消息设置延迟毫秒值
                if(delayTimes>0L){
                    message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
                }
                LOGGER.info("send orderId:-----------------{}",System.currentTimeMillis());
                return message;
            }
        });
        LOGGER.info("send orderId:{}",message);
    }
}
